import {
    api,
    util,
    dialog,
    clickIncrement,
    clearIncrement,
    forms,
    storage
} from '../../../../js/util';
import {
    area,
    share
} from "../../../../js/modules/gloab";
import {
    pagesInfo,
    router
} from '../../../../js/router';
import {
    $ecCountDown
} from '../../../../components/index.js'
import {
    profile
} from "../../../../js/modules/store.js";
import {
    detail,
    mall,
    list,
    scant,
    comments,
    specModel
} from '../../../../js/modules/mall';
import {
    activities
} from '../../../../js/modules/market';
import {
    coupon
} from '../../../../js/modules/market';
import {
    order,
    cart,
    grouporder
} from '../../../../js/modules/order';
import {
    theme
} from '../../../../js/modules/theme';
import authorize from '../../../../js/modules/authorize';
import BasePage from '../../../../js/common/base-page'
import {
    setStorageSync
} from '../../../../js/compatible';

import {
    deepClone,
    isEmpty
} from '../../../../js/newUtil';
import {
    getViewListSize,
    drawCanvas,
    getImgList,
} from '../../../js/canvas'

import {
    formatCanvasData
} from './canvasData'

const app = getApp()

BasePage({
    pageKey: "",
    validateLogin: false,
    /**
     * 页面的初始数据
     */
    data: {
        imgDomain: api.imgDomain,
        enableOss: api.enableOss,
        pagetype: 0, //0:通用 1:拼团  2:预售 3:特价
        id: 0,
        productId: 0,
        discountId: 0,
        discountType: 0,
        productData: [],
        editionInfo: null,
        annexs: [],
        coupons: [],
        couponscount: 0,
        index: 0,
        goodSpecific: [],
        productUnitText: "",
        swiperImg: [],
        pics: [],
        intropics: [],
        productVideo: [],
        productDisplayTags: [],
        isStart: 1,
        tablist: ['图文详情', '商品参数', '售后保障'],
        activeIndex: 0,
        sliderOffset: 10,
        sliderLeft: 10,
        slidewidth: 0,
        showStyle: 'view',
        guessList: [], //猜你喜欢商品列表
        hasCang: '', //是否收藏
        isScanty: false,
        quantityDigits: 0, //数量小数位数
        priceDigits: 0, //价格小数位数
        decimalDigits: 0, //金额小数位数
        openComment: false, //是否开启评价
        showProductSells: false, //是否显示销量
        isLogin: false, //是否登录
        showRetailPrice: false, //是否显示建议零售价
        productCommentInfo: {}, //商品评论信息
        supplierCommentInfo: {}, //店铺评论信息
        selectSpectValues: [], //选择的规格值
        spectStyle: 0, //规格显示样式
        goodsIndex: -1, //当前选中货口索引
        specifictions: [], //规格信息
        location: app.globalData.location,
        ddressAssignDepot: false,
        proprietorWaterMark: "", //图片水印
        addr: {
            area: "",
            code: ""
        },
        showPosterShadow: false, //海报弹层

        windowWidth: 0, //屏幕宽度
        windowHeight: 0, //屏幕高度
        contentHeight: 0, //内容高度
        thinkList: [], //文字超出换行处理
        lineHeight: 30, //固定值
        contentTitle: "", //商品标题
        subTitle: '', //副标题
        price: "", //商品价格
        delPrice: "", //划线价
        canvasUrl: "",
        qrCode: "", //小程序码https图片路径
        goodsInfoImg: "", //商品图片
        logo: "",
        downlogo: "",
        saveBtn: false, //保存图片按钮
        enableSKUTranslated: false, //不同规格单位换算关系不相同
        specObj: {}, //区间值
        packageList: [], //优惠套餐
        listId: [],
        mainColor: '', //主题色
        isIphoneX: app.globalData.isIphoneX, //适配手机
        Currency: '', //货币符号
        NoLoginShowPrice: false, //
        couponImg: '../../../../assets/images/disableCoupon.png',
        showLive: false, //显示直播
        showMinService: false, //显示客服
        showPhone: false, //显示电话
        phone: '', //电话号码
        CartName: '', //购物车显示名称
        // isLogin:true,//判断是否登录
        showModalImg: false,
        imgsList: [],
        idx: 0, //查看大图索引
        FieldDisplayName: [],
        IntroDisplayField: {},
        fieldDetail: [], //
        listState: true,
        pathUrl: '',
        filePath: '',
        IsGoodsTrading: false, //判断积分
        GoodsUnitDisplayMode: 0, //单位展示模式
        ShowVendorName: false,
        isAllPanic: false,
        FrontShowStockDetail: false,
        showPanicTime: true, // 是否显示特价结束时间信息
        DisplayBatchJoinCartArea: false, // 组合列表模式，是否展示批量加购交互区域
        DisplaySpecHorizontalSwitchArea: false, // 组合列表模式，是否展示规格横向切换区域
        BatchJoinCartUnits: [], // 批量加购时的单位列表
        barStyle: '1', // 顶部导航样式，2文字居中，3透明顶部
        navigationTitle: '商品详情',
        titleBarList: [{
                name: '详情',
                isCheck: true
            },
            {
                name: '商品参数',
                isCheck: false
            },
            {
                name: '售后保障',
                isCheck: false
            }
        ]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const query = wx.createSelectorQuery()
        query.select('#selector-params').boundingClientRect()
        query.exec(function (res) {
            console.log('高度------', res);
        });


        console.log('商品详情onload', options)
        if (options.id <= 0 && !options.scene) {
            //数据加载错误
            return;
        }
        //解析扫描商品详情小程序码中的scene
        let scene = "";
        if (options.scene && options.scene.indexOf("_") > -1) {
            let sceneStr = decodeURIComponent(options.scene);
            if (sceneStr.split("_").length == 5) {
                //_是我们定义的参数链接方
                options.id = sceneStr.split("_")[0];
                options.ptype = sceneStr.split('_')[1];
                options.productId = sceneStr.split('_')[2];
                options.discountid = sceneStr.split('_')[3];
                options.discounttype = sceneStr.split('_')[4];
            } else {
                scene = sceneStr;
            }
        }
        let pagetype = (options.ptype != undefined && options.ptype != "undefined") ? options.ptype : 0;
        var storeInfo = authorize.getEntity();
        if (scene == "" && storeInfo) {
            scene = storeInfo.fkFlag + "_" + storeInfo.fkId + "_" + storeInfo.manager.ManagerId;
        }
        let path = encodeURIComponent(`?ptype=${pagetype}&id=${options.id || 0}&discounttype=${options.discounttype || 0}&discountid=${options.discountid || 0}&scene=${scene}`);
        this.setData({
            isLogin: authorize.isLogin("store"),
            pagetype: pagetype,
            id: options.id || 0,
            discountId: options.discountid || 0,
            discountType: options.discounttype || 0,
            pathUrl: path,
            scene: scene
        });
        this.pageKey = pagetype == 3 ? 'panicBuyDeail' : 'productDetail';
        this.data.fkId = app.dns.proprietorId;
        this.data.fkFlag = app.dns.proprietor;

        //配置
        this.getWholesaleConfig();

        let that = this;
        wx.getSystemInfo({
            success: function (res) {
                that.setData({
                    slidewidth: (res.windowWidth / that.data.tablist.length) - 20,
                });
            }
        });

        this.outofstock = this.selectComponent("#outofstock");
        this.fasterComponent = this.selectComponent("#fasterComponent");
        this.stockdistribution = this.selectComponent("#stockdistribution");
        this.getShareInfo();
    },

    onPageScroll: function (e) {},
    //点击标题切换
    handleTitleBarItem(event) {
        let index = event.currentTarget.dataset.index
        let barList = this.data.titleBarList
        barList.forEach(item => {
            item.isCheck = false
        })
        barList[index].isCheck = true
        this.setData({
            titleBarList: barList
        })
        if (index == 0) {
            wx.pageScrollTo({
                selector: '#selector-detail'
            })
        } else if (index == 1) {
            wx.pageScrollTo({
                selector: '#selector-params'
            })
        } else if (index == 2) {
            wx.pageScrollTo({
                selector: '#selector-service'
            })
        }

    },
    // 优惠套餐
    packageDetail: function (id) {
        var that = this;
        var data = {
            ProductId: id
        };
        var listid = [];
        comments.getSaleDetail(data, function (content) {
            if (content.Success) {
                var list = content.Content;
                for (var i = 0; i < list.length; i++) {
                    listid.push(list[i].Id);
                    // var productList = list[i].ProductList;
                    that.gdList(list[i]);
                }
                that.setData({
                    packageList: list,
                    listId: JSON.stringify(listid)
                })
                // console.log(list,'===1===packageList');
            }
        })
    },
    gdList(item) {
        let that = this;
        let productList = item.ProductList || [];
        let originalPrice = 0,
            packedSalePrice = 0;
        for (let i = 0; i < productList.length; i++) {
            let product = productList[i];
            let goodsList = product.GoodsList || [];
            if (item.Mode == 1) {
                item.proNum = that.proList(productList);
                for (let j = 0; j < goodsList.length; j++) {
                    let goods = goodsList[j];
                    originalPrice += goods.OriginalTotal;
                    packedSalePrice += goods.PackedSaleTotal;
                }
            } else {
                item.proNum = productList.length;
                originalPrice += goodsList.length > 0 ? goodsList[0].OriginalTotal : 0;
                packedSalePrice += goodsList.length > 0 ? goodsList[0].PackedSaleTotal : 0;
            }
        }
        item.OriginalPrice = originalPrice;
        item.PackedSalePrice = packedSalePrice;
    },
    proList(item) {
        let count = 0;
        for (var i = 0; i < item.length; i++) {
            var goods = item[i].GoodsList;
            count += goods.length;
        }
        return count;
    },
    /**加载商品详情 */
    loadCommonDetail(pagetype) {
        let that = this;
        let productId = this.data.id;
        detail.loadProductDetail(pagetype, {
            pid: productId
        }, (res) => {
            let {
                IntroDisplayField
            } = that.data;
            res = res.Content;
            let goodlist = res.Goods || [],
                product = res.Product || {},
                respic = res.Pics || [],
                specifictions = res.Specifictions || [],
                editionInfo = (res.EditionInfo && Object.keys(res.EditionInfo).length > 0) ? res.EditionInfo : null,
                annexs = res.Annexs || [];
            let productData = product;
            productData.FKId = productData.SupplierId;
            productData.ProductCode = productData.ProductCode || "";
            //兼容商品起订量显示
            productData.SBuyUpperLimit = productData.BuyUpperLimit || 0;
            productData.SBuyLowerLimit = productData.BuyLowerLimit || 0;
            let status = productData.Shelved;
            let shelved = productData.Status;
            //初始化选择框
            specModel.checkedSpecValueEvent(specifictions);
            //如果不同规格单位换算关系相同，则构建转换关系文本
            let productUnitText = '';
            if (productData.EnableSKUTranslated != 1) {
                let units = (res.Goods[0] || {}).AuxiliaryUnits || [];
                productUnitText = detail.loadUnitContext(units, productData.Unit);
            }
            let Extends = res.Extends;
            if (Extends.length > 0) {
                for (var j = 0; j < Extends.length; j++) {
                    let itemKey = 'ExtAttr' + Extends[j].Id;
                    Extends[j].show = IntroDisplayField[itemKey];
                }
            }
            that.setData({
                productId: productData.ProductId,
                productData: productData,
                editionInfo: editionInfo,
                annexs: annexs,
                goodlist: goodlist,
                swiperImg: this.parsePics(respic),
                pics: this.parsePics(respic),
                productUnitText: productUnitText,
                productVideo: res.Video,
                productDisplayTags: res.DisplayTags,
                specifictions: specifictions,
                fieldDetail: Extends,
                enableSKUTranslated: productData.EnableSKUTranslated == 1 ? true : false,
                DisplayBatchJoinCartArea: res.DisplayBatchJoinCartArea,
                DisplaySpecHorizontalSwitchArea: res.DisplaySpecHorizontalSwitchArea,
                BatchJoinCartUnits: res.BatchJoinCartUnits || []
            });
            try {
                //解析京东外部链接style里面的背景图 
                util.linkParseImg(productData.Intro, (intro) => {
                    let content = util.decoratePicSrc(intro, that.data.imgDomain);
                    // .replace(/(https:\/\/www)|(https:\/\/)/, "http://")
                    content = content.replace(/()+/ig, "\n");
                    // console.log(content,'----');
                    that.setData({
                        richtext_content: content
                    })
                });
                let guarantee = util.decoratePicSrc(productData.Guarantee || "", that.data.imgDomain);
                guarantee = guarantee.replace(/()+/ig, "\n");
                // console.log(guarantee,'---guarantee');
                that.setData({
                    richtext_guarantee: guarantee
                })
            } catch (e) {

            }
            that.loadGoodSpecific(pagetype);
            let pageTitle = pagetype == 3 ? '特价商品详情' : '商品详情';
            that.pageInfo = {
                pageTitle: pageTitle,
                detailText: productData.ProductName,
                parameter: `ProductId=${productId}`
            };
        });
        //优惠套餐
        that.packageDetail(that.data.id);
    },
    parsePics(respic) {
        let pics = [];
        if (respic != undefined && respic != null) {
            for (let i = 0; i < respic.length; i++) {
                let p = respic[i];
                if (p.VirtualPath != "" && p.VirtualPath != undefined) {
                    pics.push({
                        Src: p.VirtualPath
                    });
                }
            }
        }
        return pics;
    },
    /**加载限时特价信息 */
    loadPanicInfo(productData, goodSpecific) {
        let that = this;
        detail.loadPanicProduct(that.data.discountId, productData.ProductId, (res) => {
            if (!res || res.length == 0) {
                // 当没有特价信息时，将页面中的商品重置为普通商品类型，不显示特价区域
                if (that.data.pagetype == 3) {
                    that.setData({
                        pagetype: 1
                    })
                }
                return
            }
            res = res.map(item => {
                item.type = 3
                return item
            })
            // 特价商品单位改为对应规格的单位,这段代码后续可以考虑删除
            for (let i in goodSpecific) {
                for (let j in res) {
                    let panicGoods = res[j].PanicGoods || []
                    for (let k in panicGoods) {
                        if (panicGoods[k].GoodsId == goodSpecific[i].GoodsId) {
                            res[j].PanicGoods[k].AuxUnit = goodSpecific[i].Unit
                            // 商品规格对应的特价状态和时间
                            goodSpecific[i].IsStart = res[j].IsStart
                            goodSpecific[i].StartTime = res[j].StartTime
                            goodSpecific[i].EndTime = res[j].EndTime
                        }
                    }
                }
            }
            productData.PanicBuy = deepClone(res)
            let p = res[0];
            //结束时间
            if (p.IsStart == 1) {
                productData.EndTime = p.EndTime;
                // console.log(p.EndTime,'=====endtime');
                that.setCountdown(p.EndTime);
            } else {
                // that.setCountdown(p.StartTime); //距离开始
                that.setCountdown(p.StartTime);
            }
            productData.PanicGoods = p.PanicGoods;
            //获取限时特价的价格区间
            let minPrice = p.PanicGoods[0].Price;
            let maxPrice = p.PanicGoods[p.PanicGoods.length - 1].Price;
            p.PanicGoods.map(function (item) {
                if (item.Price > maxPrice) {
                    maxPrice = item.Price;
                }
                if (item.Price < minPrice) {
                    minPrice = item.Price;
                }
            });
            productData.MinPaicPrice = minPrice;
            productData.MaxPaicPrice = maxPrice;
            productData.CostPrice = p.CostPrice;
            productData.priceMinMode = {
                PriceType: productData.pricetype,
                IsDeduction: productData.isdeduction,
                SalesPrice: productData.minprice,
                SalesIntegral: productData.minintegral,
                DeductRate: productData.deductrate,
                SaleMode: productData.salemode
            }
            productData.priceMaxMode = {
                PriceType: productData.pricetype,
                IsDeduction: productData.isdeduction,
                SalesPrice: productData.maxprice,
                SalesIntegral: productData.maxintegral,
                DeductRate: productData.deductrate,
                SaleMode: productData.salemode
            }
            if (p.PanicGoods.length > 0) {
                productData.isPanic = true;
            }
            for (let x = 0; x < res.length; x++) {
                // 当特价活动开始时才将特价信息附加到规格上
                if (res[x].IsStart == 1) {
                    detail.decorate_specific(goodSpecific, res[x].PanicGoods, 3);
                }
            }
            for (var i = 0; i < goodSpecific.length; i++) {
                that.unitList(goodSpecific[i].AuxiliaryUnits, goodSpecific[i].UnitPrices, goodSpecific[i].CartCount, goodSpecific[i])
                goodSpecific[i].show = false;
            }
            if (this.data.addressAssignDepot) {
                this.selectComponent("#deliveryComponent").getDefaultAddress();
            }
            // else {
            //   this.selectedAdress({ detail: { Province: "", City: "", Area: "", Code: "" } })
            // // }
            productData.allUnit = p.AuxUnit;
            console.log(goodSpecific, '=====goodSpecific', this.data.goodsIndex)
            if (this.data.goodsIndex > -1) {
                productData.BuyUpperLimit = goodSpecific[this.data.goodsIndex].SBuyUpperLimit || 0;
                productData.BuyLowerLimit = goodSpecific[this.data.goodsIndex].SBuyLowerLimit || 0;
                productData.SBuyUpperLimit = goodSpecific[this.data.goodsIndex].BuyUpperLimit || 0;
                productData.SBuyLowerLimit = goodSpecific[this.data.goodsIndex].BuyLowerLimit || 0;
                productData.Price = goodSpecific[this.data.goodsIndex].Price || 0;
            }
            that.pageKey = 'panicBuyDeail';
            that.setData({
                goodSpecific: goodSpecific,
                productData: productData,
                isStart: p.IsStart,
                pagetype: 3,
                discountId: p.Id,
                discountType: 3,
            }, function () {
                that.isAllPanic();
            });
        });
    },
    /**加载货品规格信息列表 */
    loadGoodSpecific(pagetype) {
        let that = this;
        let {
            id,
            discountId,
            discountType,
            spectStyle,
            isLogin,
            productData,
            goodlist,
            specifictions,
            swiperImg
        } = this.data;
        let areaCode = area.getCacheLocation().Code;
        let param = {
            productId: id,
            discountId: discountId,
            discountType: discountType,
            spectStyle: spectStyle,
            areaCode: areaCode
        }
        detail.loadProductInstantInfo(param, goodlist, productData, (goods, res) => {
            let goodSpecific = goods;
            console.log('当前商品信息', goods)
            // 判断是否未登录时的要显示商品价格
            for (let i in goods) {
                if (goods[i].PriceType == -1) {
                    productData.PriceType = -1
                    break
                }
            }
            if (spectStyle == 1) {
                specModel.setGoodsIndex(specifictions, goodSpecific, -1, (specDecorate) => {
                    if (specDecorate.goodsIndex != -1) {
                        let pics = goodlist[specDecorate.goodsIndex].Pics;
                        if (pics && pics.length > 0) {
                            swiperImg = that.parsePics(pics)
                        } else {
                            swiperImg = that.data.pics;
                        }
                    } else {
                        swiperImg = that.data.pics;
                    }
                    that.data.goodsIndex = specDecorate.goodsIndex;
                    that.setData({
                        swiperImg: swiperImg,
                        goodsIndex: specDecorate.goodsIndex,
                        goodSpecific: goodSpecific,
                        productData: productData,
                        specObj: res.Content
                    });
                })
            } else {
                that.setData({
                    goodSpecific: goodSpecific,
                    productData: productData,
                    specObj: res.Content
                });
            }
            //把活动信息附加到商品对象     
            activities.loadProductActivities([that.data.productData], true, 0, areaCode, function (gres) {
                productData = gres[0];
                console.log(gres)
                goodSpecific.map((g) => {
                    detail.decoratePromotion(g, productData.Promotions);
                })
                res.Content.MinSalesPrice = (res.Content.MinSalesPrice).toFixed(2)
                res.Content.MaxSalesPrice = (res.Content.MaxSalesPrice).toFixed(2)
                for (var i = 0; i < goodSpecific.length; i++) {
                    that.unitList(goodSpecific[i].AuxiliaryUnits, goodSpecific[i].UnitPrices, goodSpecific[i].CartCount, goodSpecific[i])
                    goodSpecific[i].show = false;
                }
                if (pagetype == 3) {
                    productData.market = ['特价']
                }
                that.setData({
                    productData: productData,
                    goodSpecific: goodSpecific,
                    specObj: res.Content
                });
                //登录状态才调用特价接口
                if (isLogin || (that.data.discountType == 3 && that.data.discountId > 0)) {
                    that.loadPanicInfo(that.data.productData, goodSpecific);
                } else {
                    that.setData({
                        showPanicTime: false
                    })
                }
            });
            if (this.data.addressAssignDepot) {
                this.selectComponent("#deliveryComponent").getDefaultAddress();
            }
            that.loadCoupons(that.data.goodsIndex);
            that.getCommentsInfo();
            that.getSupplierCommentInfo();
            //猜你喜欢
            that.loadGuessList();
        });
    },
    unitList(AuxiliaryUnits, UnitPrices, CartCount, goodlist) {
        let {
            quantityDigits
        } = this.data;
        for (var i = 0; i < AuxiliaryUnits.length; i++) {
            var item = AuxiliaryUnits[i];
            var t = detail.parseRule(UnitPrices, item.Translated, item.Qty || 0, false);
            if (t.has) {
                item.price = t.price;
                if (t.integral) {
                    item.integral = t.integral;
                }
            }
            var otherAuxiliaryUnits = AuxiliaryUnits.filter(unit => {
                return unit.Translated != item.Translated
            });
            var otherUnitQuantity = 0;
            if (otherAuxiliaryUnits && otherAuxiliaryUnits.length > 0) {
                otherAuxiliaryUnits.map((child, idx) => {
                    if (child.Qty != undefined && child.Qty > 0) {
                        otherUnitQuantity += (child.Qty || 0) * (child.Translated || 1);
                    }
                });
            }
            item.BuyLowerLimit = goodlist.SBuyLowerLimit > 0 && goodlist.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyLowerLimit - otherUnitQuantity, quantityDigits) : 0;
            item.BuyUpperLimit = goodlist.SBuyUpperLimit > 0 && goodlist.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyUpperLimit - otherUnitQuantity, quantityDigits) : 0;
            item.Stock = goodlist.SStock > 0 && goodlist.SStock > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SStock - otherUnitQuantity, quantityDigits) : 0;
            item.IsSingle = goodlist.IsSingle;
            item.DefaultUnit = item.Name;
            item.ZeroStockBuy = goodlist.ZeroStockBuy;
            item.SpecValue = goodlist.SpecValue;
            item.ProductId = goodlist.ProductId;
            item.DiscountId = goodlist.DiscountId;
            item.DiscountType = goodlist.DiscountType;
            AuxiliaryUnits[i] = item;
            if (this.data.GoodsUnitDisplayMode == 0 && item.Translated == (goodlist.Translated || goodlist.Radix)) {
                goodlist.BuyLowerLimit = item.BuyLowerLimit;
                goodlist.BuyUpperLimit = item.BuyUpperLimit;
                goodlist.Stock = item.Stock;
            }
        }
    },
    /**
     * 是否全是特价
     */
    isAllPanic() {
        let isAllPanic = true;
        this.data.goodSpecific.map((item) => {
            if (!item.isPanic) {
                isAllPanic = false
            }
        })
        this.setData({
            isAllPanic: isAllPanic
        })
    },
    /**倒计时 */
    formatNumber(n) {
        n = n.toString()
        return n[1] ? n : '0' + n
    },
    setCountdown(time) {
        var that = this;
        let newTime = new Date().getTime();
        let endTime = new Date(time.replace(/-/g, "/")).getTime();
        let remainTime = endTime - newTime;
        let obj = null;
        let t = '';
        // 如果活动未结束，对时间进行处理
        if (remainTime > 0) {
            let time = remainTime / 1000;
            // 获取天、时、分、秒
            let day = parseInt(time / (60 * 60 * 24));
            let hou = parseInt(time % (60 * 60 * 24) / 3600);
            let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
            let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
            obj = {
                day: that.formatNumber(day),
                hou: that.formatNumber(hou),
                min: that.formatNumber(min),
                sec: that.formatNumber(sec)
            }
        }
        // console.log(obj,'=======sec');
        that.timeCountDown = setTimeout(function () {
            that.setData({
                c1: obj.day,
                c2: obj.hou,
                c3: obj.min,
                c4: obj.sec
            })
            that.setCountdown(time)
        }, 1000)
        if (remainTime <= 0) {
            clearTimeout(that.timeCountDown);
        }
        // that.c1 = new $ecCountDown({
        //   date: time,
        //   render(date) {
        //     console.log(date,'======new $ecCountDown');
        //     const days = this.leadingZeros(date.years * 365 + date.days, 2)
        //     const hours = this.leadingZeros(date.hours, 2)
        //     const min = this.leadingZeros(date.min, 2)
        //     const sec = this.leadingZeros(date.sec, 2)

        //     that.setData({
        //       c1: days,
        //       c2: hours,
        //       c3: min,
        //       c4: sec
        //     })
        //   },
        // });
    },
    /**加载优惠劵 */
    loadCoupons(goodsIndex) {
        let that = this;
        coupon.loadProductCoupons(that.data.id, function (content) {
            that.data.coupons = content;
            that.setData({
                couponscount: content.length,
                coupons: content
            });
        });
    },
    /**
     * 获得评论信息
     */
    getCommentsInfo() {
        let that = this;
        comments.getCommentsInfo({
            pid: that.data.id,
            gid: 0,
            fkFlag: that.data.fkFlag,
            fkId: that.data.fkId
        }, function (res) {
            if (res.Success) {
                that.setData({
                    productCommentInfo: res.Content
                });
            }

        });
    },
    /**
     * 显示缺货登记
     */
    onShowScantyEvent: function (e) {
        var that = this;
        var goods = e.detail;
        that.outofstock.setData({
            scantyProduct: goods,
        })
        that.outofstock.openScanyDialog(e);
    },
    showScantyModal: function (e) {
        var that = this;
        var goods = that.data.guessList[e.currentTarget.dataset.idx];
        that.outofstock.setData({
            scantyProduct: goods,
        })
        that.outofstock.openScanyDialog(e);
    },
    /**
     * 显示库存分布
     */
    showStockDistribution(e) {
        var goods = e.detail;
        this.stockdistribution.setData({
            product: goods,
            isGoodsStock: true
        })
        this.stockdistribution.showStockModal(e);
    },
    /**
     * 获得店铺评论信息
     */
    getSupplierCommentInfo() {
        let that = this;
        comments.getSupplierCommentInfo({
            fkFlag: that.data.fkFlag,
            fkId: that.data.fkId
        }, function (res) {
            if (res.Success) {
                that.setData({
                    supplierCommentInfo: res.Content
                });
            }

        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function (options) {
        console.log('商品详情onshow', options)
        this.setData({
            mainColor: api.titleColor || "#e56b14",
            Currency: api.Currency || '￥',
            CartName: api.CartName || '购物车'
        });
        this.getCartCount();
    },
    /**统计购物车数量 */
    getCartCount() {
        let that = this;
        cart.get_cart_count(function (res) {
            that.setData({
                carcount: res.Content
            });
        });
    },
    /**加载商品类的配置项参数 */
    getWholesaleConfig() {
        let that = this;
        let fkid = app.dns.proprietorId;
        let fkflag = app.dns.proprietor;
        let {
            pagetype
        } = this.data;
        list.getWholesaleConfigs(
            fkid,
            fkflag,
            (content) => {
                var fieldDisplayName = content.FieldDisplayName ? content.FieldDisplayName.split(',') : [];
                var mIntroDisplayField = content.MIntroDisplayField ? content.MIntroDisplayField.split('|') : [];
                var introDisplayField = {
                    Price: false,
                    ProductCode: false,
                    PackageSpec: false,
                    BuyLimit: false,
                    BarCode: false
                };
                for (var i = 0; i < mIntroDisplayField.length; i++) {
                    introDisplayField[mIntroDisplayField[i]] = true;
                }
                that.setData({
                    openComment: content.OpenComment,
                    showRetailPrice: content.ShowRetailPrice,
                    quantityDigits: content.QuantityDigits,
                    priceDigits: content.PriceDigits,
                    spectStyle: content.GoodsDisplayMode,
                    showProductSells: content.ShowProductSells,
                    addressAssignDepot: content.AddressAssignDepot,
                    isScanty: content.IsScanty, //是否允许缺货登记
                    decimalDigits: content.DecimalDigits,
                    logo: content.LogoForMobile,
                    proprietorWaterMark: content.ProprietorWaterMark,
                    NoLoginShowPrice: content.NoLoginShowPrice, //0：建议零售价 1：不显示价格
                    CartName: api.CartName || '购物车',
                    activeIndex: Number(content.MIntroDefaultTab),
                    sliderOffset: Number(content.MIntroDefaultTab) ? wx.getSystemInfoSync().windowWidth / 3 + 10 : 10,
                    FieldDisplayName: fieldDisplayName,
                    IntroDisplayField: introDisplayField,
                    IsGoodsTrading: content.IsGoodsTrading,
                    showMinService: content.IsShowMinService,
                    GoodsUnitDisplayMode: content.GoodsUnitDisplayMode,
                    ShowVendorName: content.ShowVendorName,
                    FrontShowStockDetail: content.FrontShowStockDetail
                });
                //商品详情
                that.loadCommonDetail(pagetype);
                //商品扩展属性
                that.ProductRelate();
            });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 获取分享信息
     */
    getShareInfo: function () {
        let that = this;
        let {
            id,
            productData,
            discountType,
            discountId
        } = that.data;
        let param = {
            Proprietor: app.dns.proprietor,
            ProprietorId: app.dns.proprietorId,
            ProductId: id,
            DiscountType: discountType,
            DiscountId: discountId,
            Type: 'product'
        }
        share.getinfo(param, false, function (res) {
            let shareObj = {};
            shareObj.title = res.Title || productData.ProductName;
            shareObj.img = res.ImgSrc != '' ? api.imgDomain + res.ImgSrc : '';
            shareObj.SharePrice = res.SharePrice;
            that.setData({
                shareObj: shareObj
            })
        })
    },
    /**
     * 下载附件
     */
    loadFile: function (e) {
        var that = this;
        let url = e.currentTarget.dataset.url
        let ps = url.split('?')[1].split('=')[1];
        // ps = ps.replace('url=','');
        ps = that.data.imgDomain + ps;
        console.log(ps, '======');
        // let url = e.currentTarget.dataset.url.replace('http://','https://');
        let type = e.currentTarget.dataset.type;
        wx.showLoading({
            title: '下载中'
        })
        wx.downloadFile({
            url: ps.replace('http://', 'https://'),
            success: function (res) {
                // console.log(res.tempFilePath,'--------res.tempFilePath');
                that.setData({
                    filePath: res.tempFilePath
                })
                if (type == 'jpeg' || type == 'jpg' || type == 'png' || type == 'bmp' || type == 'gif' || type == 'ico') {
                    wx.saveImageToPhotosAlbum({
                        filePath: that.data.filePath,
                        success(res) {
                            wx.showModal({
                                content: '图片已下载到相册',
                                showCancel: false,
                                confirmText: '好的',
                                confirmColor: '#333',
                                success: function (res) {},
                                fail: function (res) {}
                            })
                            wx.hideLoading()
                        },
                        fail: function (res) {
                            wx.hideLoading()
                            wx.showModal({
                                title: '提示',
                                content: '需要您授权保存相册',
                                showCancel: false,
                                success() {
                                    wx.openSetting({
                                        success(settingdata) {
                                            if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: '获取授权成功，再次保存图片即可成功',
                                                    showCancel: false
                                                })
                                            } else {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: '获取授权失败，无法保存到相册',
                                                    showCancel: false
                                                })
                                            }
                                        },
                                        complete(complet) {
                                            console.log('complet', complet)
                                        }
                                    })
                                }
                            })
                        }
                    })
                } else if (type == "mp4" || type == "mp3") {
                    wx.setClipboardData({
                        data: url.replace("http://", "https://"),
                        success(res) {
                            wx.hideLoading()
                            util.tips('复制成功，请在浏览器中进行下载');
                        }
                    })
                } else if (type == "zip" || type == "rar") {
                    var fs = wx.getFileSystemManager();
                    fs.saveFile({
                        tempFilePath: that.data.filePath,
                        success(res) {
                            wx.hideLoading()
                            const savedFilePath = res.savedFilePath
                            console.log(savedFilePath, '========savedFilePath');
                        },
                        fail() {
                            wx.hideLoading()
                        }
                    })
                } else {
                    wx.hideLoading()
                    wx.openDocument({
                        filePath: that.data.filePath,
                        showMenu: true,
                        success: function (res) {}
                    })
                    // wx.saveFile({
                    //   tempFilePath:that.data.filePath,
                    //   success(res){
                    //     wx.showModal({
                    //       content: '文件已下载成功',
                    //       showCancel: false,
                    //       confirmText: '好的',
                    //       confirmColor: '#333',
                    //       success: function (res) {
                    //         if (res.confirm) { }
                    //       },
                    //       fail: function (res) { }
                    //     })
                    //   }
                    // })
                }
            },
            fail: function (err) {
                wx.hideLoading()
                util.tips(err.errMsg);
            }
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        let {
            id,
            pagetype,
            discountId,
            discountType,
            shareObj
        } = this.data;
        var storeInfo = authorize.getEntity();
        let scene = "";
        if (storeInfo) {
            scene = storeInfo.fkFlag + "_" + storeInfo.fkId + "_" + storeInfo.manager.ManagerId;
        }
        let path = pagesInfo.productDetail.url + `?ptype=${pagetype}&id=${id}&discounttype=${discountType}&discountid=${discountId}&scene=${scene}`;
        return {
            title: shareObj.title,
            path: path,
            imageUrl: shareObj.img
        }
    },
    /**
     * 分享朋友圈（beta版本，仅限安卓手机）
     */
    onShareTimeline: function () {
        let {
            id,
            pagetype,
            discountId,
            discountType,
            shareObj
        } = this.data;
        var storeInfo = authorize.getEntity();
        let scene = "";
        if (storeInfo) {
            scene = storeInfo.fkFlag + "_" + storeInfo.fkId + "_" + storeInfo.manager.ManagerId;
        }
        let path = `ptype=${pagetype}&id=${id}&discounttype=${discountType}&discountid=${discountId}&scene=${scene}`;
        return {
            title: shareObj.title,
            query: path,
            imageUrl: shareObj.img
        }
    },
    changeCurrent: function (res) {
        this.setData({
            sliderOffset: res.detail.currentNum.offsetLeft + 10,
            activeIndex: res.detail.currentNum.id
        });
    },
    //底部收藏
    collection: function () {
        let favouriteId = this.data.productData.FavoriteId;
        if (favouriteId > 0) {
            this.delFavorite(favouriteId);
        } else {
            this.addFavorite();
        }
    },
    /**添加收藏 */
    addFavorite() {
        let param = {
            ProductFKId: this.data.productData.FKId,
            ProductId: this.data.productId
        };
        let that = this;
        let {
            productData,
            isLogin
        } = this.data;
        if (!isLogin) {
            // router.redirect({
            //   path: "login",
            //   params: {
            //     role: "store"
            //   }
            // });
            this.toLogin()
        } else {
            mall.addFavorite(param, function (res) {
                let key = "productData.FavoriteId";
                if (res.Success) {
                    that.setData({
                        [key]: res.Content
                    });
                    util.success("商品收藏成功！");
                } else {
                    util.tips("商品收藏失败:" + res.Message);
                }
            });
        }
    },
    /**取消收藏 */
    delFavorite(favouriteId) {
        let that = this;
        mall.delFavorite(favouriteId, function (res) {
            let key = "productData.FavoriteId";
            if (res.Content == 1) {
                that.setData({
                    [key]: 0
                });
                util.success("取消收藏成功！");
            } else if (res.Content == -11) {
                util.tips("请先登录，再进行此操作！");
            } else {
                util.tips(res.Message);
            }
        });
    },
    /**
     * 猜您喜欢
     */
    loadGuessList() {
        let that = this;
        let param = {
            PageIndex: 1,
            PageSize: 48
        };
        setTimeout(function () {
            detail.loadProductsByRandom(param, that.data.id, function (content) {

                that.setData({
                    guessList: content
                });
                for (let i = 0; i < content.length; i++) {
                    content[i].SupplierId = that.data.productData.FKId;
                    //这里需要把原始值用另一个字段存下来，方便后面计算时用原始值计算
                    content[i].SBuyLowerLimit = content[i].BuyLowerLimit || 0;
                    content[i].SBuyUpperLimit = content[i].BuyUpperLimit || 0;
                    content[i].SStock = content[i].Stock;
                }
                activities.loadProductActivities(content, false, 0, that.data.addr.code, function (gres) {
                    for (var i = 0; i < gres.length; i++) {
                        that.unitList(gres[i].AuxiliaryUnits, gres[i].UnitPrices, gres[i].CartCount, gres[i])
                    }
                    that.setData({
                        guessList: gres
                    });
                });
                // console.log(that.data.guessList,'====');
            });
        }, 1000);

    },
    /**显示可领取优惠劵 */
    showCoupons(e) {
        router.navigate({
            path: "receivedCouponList",
            params: {
                ProductId: this.data.id
            }
        });

    },
    /**隐藏优惠劵层 */
    hideModal() {
        let that = this;
        dialog.hideModal(that, 'showModalStatus')
    },
    /**
     * 计算优惠券数量
     */
    caculateCouponsCount(goodsIndex) {
        let {
            coupons,
            spectStyle,
            goodSpecific
        } = this.data;
        let couponscount = 0;
        if (spectStyle == 0) {
            couponscount = coupons.length;
            return couponscount;
        }
        let goods = goodSpecific[goodsIndex];
        coupons.map((item) => {
            if (item.GoodsIds != undefined && item.GoodsIds != "") {
                couponscount = couponscount + (item.GoodsIds.split(",").indexOf(goods ? goods.GoodsId : 0 + "") > -1 ? 1 : 0);
            } else {
                couponscount = couponscount + 1;
            }
        })
        return couponscount;
    },
    /**
     * 货品切换事件
     */
    onGoodsChangeEvent(e) {
        var that = this;
        let {
            product,
            goods,
            goodsIndex,
            currentIndex
        } = e.detail;
        let {
            swiperImg,
            coupons,
            goodlist,
            goodSpecific
        } = this.data;
        if (goodsIndex > -1) {
            that.unitList(goods.AuxiliaryUnits, goods.UnitPrices, goods.CartCount, goods)
            goodSpecific[goodsIndex] = goods;
            let pics = goodlist[goodsIndex].Pics;
            if (pics && pics.length > 0) {
                swiperImg = currentIndex == -1 ? this.data.pics : this.parsePics(pics);
            } else {
                swiperImg = this.data.pics;
            }
            if (goodSpecific[goodsIndex].isPanic) {
                let p = goodSpecific[goodsIndex] || {}
                if (p.IsStart == 1) {
                    if (p.EndTime) {
                        clearTimeout(that.timeCountDown)
                        that.setCountdown(p.EndTime)
                    }
                } else {
                    if (p.StartTime) {
                        clearTimeout(that.timeCountDown)
                        that.setCountdown(p.StartTime)
                    }
                }
            }
        } else {
            swiperImg = this.data.pics;
        }
        this.setData({
            couponscount: this.caculateCouponsCount(goodsIndex),
            swiperImg: swiperImg,
            goodsIndex: goodsIndex,
            currentIndex: currentIndex || goodsIndex,
            goodSpecific: goodSpecific,
            productData: product
        })
    },
    /**
     * 组合列表模式时，批量修改商品规格数量/单位
     */
    onGoodsChangeMultipleEvent(e) {
        var that = this
        let {
            product,
            goodSpecific,
            lastItemIndex,
            currentIndex
        } = e.detail
        let {
            swiperImg,
            goodlist
        } = this.data
        swiperImg = this.data.pics
        if (lastItemIndex > -1) {
            for (let i = 0; i < goodSpecific.length; i++) {
                let goods = goodSpecific[i] || {}
                that.unitList(goods.AuxiliaryUnits, goods.UnitPrices, goods.CartCount, goods)
                goodSpecific[i] = goods
            }
            let pics = goodlist[lastItemIndex].Pics
            if (pics && pics.length > 0) {
                swiperImg = currentIndex == -1 ? this.data.pics : this.parsePics(pics);
            }
        }
        this.setData({
            couponscount: this.caculateCouponsCount(lastItemIndex),
            swiperImg: swiperImg,
            goodsIndex: lastItemIndex,
            currentIndex: lastItemIndex,
            goodSpecific: goodSpecific,
            productData: product
        })
    },
    packBatchAddCart(e) {
        var that = this;
        this.selectComponent("#productSpec").onAddCarEvent(() => {
            util.success("加入成功！", function () {
                that.getCartCount();
            }, 600);
        });
    },
    buyMultiNow(e) {
        this.selectComponent("#productSpec").onBuyEvent();
    },
    /**跳转到购物车页面 */
    gotoCart() {
        setStorageSync('tabindex', app.dns.cartNum)
        router.switchTab({
            path: 'cart'
        });
    },
    /**跳转到首页页面 */
    onBindHome() {
        router.switchTab({
            path: "index"
        });
    },
    /**全部商品和进入店铺的底部跳转 */
    switchTablink(e) {
        let url = e.currentTarget.dataset.url;
        if (url == null || url == undefined || url == "") return;
        router.switchTab({
            path: url
        });
    },

    /**
     * 单击事件，获得goodsid（模版中不能使用wx:for-index
     */
    onClickGoodsUnitEvent: function (e) {
        this.setData({
            current_gooods_idx: e.currentTarget.dataset.gidx
        });
    },
    /**加载商品扩展信息 */
    ProductRelate() {
        let that = this;
        setTimeout(function () {
            detail.loadProductRelate(that.data.id, function (res) {
                that.setData({
                    Relate: res
                });
            });
        }, 1000)

    },

    onSkipDetail(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        // app.globalData.product_list.rule_id = id;
        router.navigate({
            path: "promotionDetail",
            params: {
                id: id
            }
        })
    },
    toDetail(e) {
        let pagetype = e.currentTarget.dataset.pagetype;
        let linkparam = e.currentTarget.dataset.linkparam;
        let loadcomplate = e.currentTarget.dataset.loadcomplate;
        if (loadcomplate != 1) return;
        let url = "productDetail";
        if (pagetype == 1 || pagetype == 2) {
            url = "groupDetail";
        }
        theme.routerTo(url, linkparam);

    },
    onBindContactEvent(e) {
        // console.log(e)
    },
    /**
     * 隐藏遮罩层
     */
    hideModal: function () {
        dialog.hideModal(this, 'showModalStatus')
    },
    onUnload: function (e) {
        clearIncrement();
        if (this.timeCountDown) {
            clearTimeout(this.timeCountDown)
        }
        this.data.pre_page = this.getPreData();
        if (this.data.pre_page) {
            this.data.pre_page.data.is_search = app.globalData.product_list.rule_id == -1;
        }
    },
    getPreData: function () {
        const pages = getCurrentPages();
        const length = pages.length;
        const prePage = pages[length - 2]; //上一页
        return prePage;
    },
    showDelivery(e) {
        this.selectComponent("#deliveryComponent").loadAdressList(e);
    },
    /**
     * 配送至弹层选择地址
     */
    selectedAdress(e) {
        let {
            pagetype
        } = this.data;
        this.setData({
            addr: {
                province: e.detail.Province,
                city: e.detail.City,
                area: e.detail.Area,
                code: e.detail.Code
            }
        }, () => {
            let {
                addr,
                productId,
                goodSpecific
            } = this.data;
            let data = {
                code: addr.code,
                productId: productId,
                goodlist: goodSpecific
            }
            detail.getStockByArea(data, (d) => {
                this.setData({
                    goodSpecific: d
                })
            })
        });

    },
    /**
     * 打开分享弹层
     */
    showShare: function (e) {
        var that = this;
        dialog.showModal(that, 'showModalStatus')
    },
    /**
     * 隐藏遮罩层
     */
    hideModal: function () {
        dialog.hideModal(this, 'showModalStatus')
    },
    /**
     * 显示海报
     */
    showPoster: function () {
        dialog.hideModal(this, 'showModalStatus')
        // console.log(this.data.productData,'=======分享',this.data.goodsIndex,this.data.goodSpecific)
        this.drawPicture();
        this.setData({
            showPosterShadow: true
        })
    },
    /**
     * 关闭海报
     */
    hidePoster: function () {
        this.setData({
            showPosterShadow: false,
            saveBtn: false
        })
    },
    initData: function (res) {
        let that = this;
        // console.log(that.data.productData,'====');
        let n = that.data.goodsIndex == -1 ? 0 : that.data.goodsIndex;
        let infoPrice = 0;
        let productData = this.data.productData || {}
        let shareObj = this.data.shareObj || {}
        if (that.data.discountType != 2) {
            infoPrice = productData.MinPaicPrice
            if (shareObj.SharePrice == 2) {
                infoPrice = productData.MinSalesPrice
            }
        }
        if (that.data.discountType == 2 && that.data.productData.PanicGoods.length > 0 && (that.data.productData.MaxPaicPrice >= that.data.productData.MinPaicPrice)) {
            infoPrice = that.data.productData.MinPaicPrice
        }
        var index = that.data.goodsIndex;
        let noPrice = that.data.productData.MinPrice
        if (shareObj.SharePrice == 2) {
            noPrice = productData.MinSalesPrice
        }
        // 价格为0，并且有积分时，海报显示所需积分
        if (that.data.goodSpecific[n].SalesIntegral > 0 && that.data.goodSpecific[n].IsDeduction != 1) {
            if (infoPrice == 0) {
                infoPrice = that.data.goodSpecific[n].SalesIntegral + '积分'
            } else {
                infoPrice = that.data.Currency + infoPrice
            }
            if (noPrice == 0) {
                noPrice = that.data.goodSpecific[n].SalesIntegral + '积分'
            } else {
                noPrice = that.data.Currency + noPrice
            }
        } else {
            if (infoPrice != 0) {
                infoPrice = that.data.Currency + infoPrice
            }
            if (noPrice != 0) {
                noPrice = that.data.Currency + noPrice
            }
        }
        if (that.data.discountType == 2 && that.data.productData.PanicGoods.length > 0 && (that.data.productData.MaxPaicPrice >= that.data.productData.MinPaicPrice)) {
            infoPrice = infoPrice + '起/' + (that.data.productData.DefaultUnit || that.data.productData.AuxUnit);
        }
        noPrice = noPrice + (that.data.goodSpecific.length > 1 ? '起' : '') + '/' + (that.data.productData.allUnit || that.data.productData.DefaultUnit || that.data.productData.AuxUnit);
        console.log(infoPrice, noPrice)
        that.setData({
            normalPageX: (res.windowWidth * 0.74 - res.windowWidth * 0.67) * 0.8, //左边文本图片X轴位置
            boxWidth: res.windowWidth * 0.74, //分享图片box宽度
            boxheight: res.windowWidth * (0.222 + 0.72 + 0.192) + 20, //分享图片box高度
            boxPageY: 0, //boxY轴位置
            imgWidth: res.windowWidth * 0.67, //商品图片宽度
            imgHeight: res.windowWidth * 0.92, //商品图片高度
            imgPageY: res.windowWidth * 0.15, //商品图片Y轴位置
            codeWidth: res.windowWidth * 0.192, //小程序码图片宽度
            codeHeight: res.windowWidth * 0.192, //小程序码图片高度
            codePageY: res.windowWidth * 0.9, //小程序码Y轴位置
            pricePageY: res.windowWidth * 0.85 + 30, //价格Y轴位置
            titlePageY: res.windowWidth * 0.85 + 70, //标题Y轴位置
            subTitlePageY: res.windowWidth * 0.85 + 140, //副标题Y轴位置
            contentTitle: that.data.productData.ProductName,
            subTitle: that.data.productData.ViceTitle,
            market: that.data.productData.market || [],
            price: that.data.goodSpecific[n].isPanic ? infoPrice : noPrice,
            grade: that.data.goodSpecific[n].SalesIntegral,
            isDeduction: that.data.goodSpecific[n].IsDeduction == 1, //是否为积分抵扣模式
            logoWidth: res.windowWidth * 0.05 * 5.5,
            logoHeight: res.windowWidth * 0.05,
        });
        let {
            imgDomain
        } = this.data;
        if (that.data.logo != "" && that.data.downlogo == "") {
            let logoUrl = imgDomain.replace("http://", "https://") + that.data.logo
            wx.downloadFile({
                url: logoUrl,
                success: function (re) {
                    that.setData({
                        downlogo: re.tempFilePath
                    });
                },
                fail: function (err) {
                    util.tips(imgDomain + err.errMsg);
                }
            });
            wx.getImageInfo({
                src: logoUrl,
                success: function (re) {
                    let logoWidth = 200
                    let logoHeight = re.height * logoWidth / re.width
                    that.setData({
                        logoWidth: logoWidth,
                        logoHeight: logoHeight
                    });
                }
            })
        }
        //网络图片转为本地图片，直接显示网络图片的话真机不显示
        var src = (this.data.swiperImg[0] != undefined && this.data.swiperImg[0].Src != '') ? this.data.swiperImg[0].Src : '/assets/images/img.png';
        var url = this.data.imgDomain + src;
        if (url != undefined && url != "") {
            that.setData({
                posterPic: url
            })
            that.getTempFile(url);
        } else {
            that.setData({
                showPosterShadow: false
            }, function () {
                util.tips("未能生成海报图");
                return;
            })
        }
    },
    //绘制海报
    drawPicture: function () {
        let that = this;
        //获取设备信息高度。计算出其他的高度等
        wx.getSystemInfo({
            success: function (res) {
                //调整海报清晰度
                that.setData({
                    windowWidth: res.windowWidth * 2,
                    windowHeight: res.windowHeight * 2,
                    canvasId: "canvas"
                });
                res.windowWidth = res.windowWidth * 2;
                res.windowHeight = res.windowHeight * 2;
                that.initData(res);
            }
        });

    },
    //临时图片路径
    getTempFile: function (url) {
        let that = this;
        let {
            imgDomain,
            imgWidth,
            imgHeight,
            windowWidth
        } = this.data;
        wx.getImageInfo({
            src: url.replace("http://", "https://"),
            success: function (res) {
                console.log(url, res)
                that.setData({
                    goodsInfoImg: res.path
                });
                // 获取图片真实信息，防止图片变形
                if (imgWidth) {
                    imgHeight = imgWidth * res.height / res.width
                    that.setData({
                        imgWidth,
                        imgHeight,
                    })
                    // 并且计算图片高度变化后的Y轴值
                    let imgPageY = windowWidth * 0.15 + (windowWidth * 0.92 - imgHeight) / 2
                    if ((imgPageY + imgHeight) < windowWidth * 1.07) {
                        that.setData({
                            imgPageY
                        })
                    }
                }
                //继续生成商品的小程序码
                that.downloadSkuQrCode();
            },
            fail: function (err) {
                console.info(err);
                util.tips(imgDomain + err.errMsg);
            }
        });
    },


    //画矩形，也是整块画布的大小，宽度是屏幕宽度，高度根据内容多少来动态设置。
    drawSquare: function (ctx, height) {
        let that = this;
        ctx.rect(
            0,
            0,
            that.data.boxWidth,
            height
        );
        ctx.setFillStyle("#fff");
        ctx.fill();
    },

    // 设置标题文字大小，并填充颜色。
    drawTitleFont: function (ctx) {
        let that = this;
        let str = that.data.contentTitle;
        let firstline;
        let secondline;
        //一行显示14个字，超过一行时
        if (str.length > 14) {
            //第一行截取前14个字符
            firstline = str.substring(0, 14);
            //两行都显示不下
            if (str.length > 28) {
                secondline = str.substr(14, 14) + "...";
            } else {
                //第二行取剩下的
                secondline = str.substr(14, str.length - 14);
            }
        } else {
            //一行就能显示时候
            firstline = str;
        }

        ctx.setFontSize(24);
        ctx.setFillStyle("#333");
        let titlePageY;
        if (that.data.subTitle && that.data.subTitle.length > 0) {
            titlePageY = that.data.titlePageY;
        } else {
            titlePageY = that.data.titlePageY + 40;
        }
        ctx.fillText(firstline, that.data.normalPageX, titlePageY);
        if (secondline) {
            ctx.setFontSize(24);
            ctx.setFillStyle("#333");
            ctx.fillText(
                secondline,
                that.data.normalPageX,
                titlePageY + 34
            );
        }
    },
    // 设置副标题文字大小，并填充颜色。
    drawSubTitleFont: function (ctx) {
        let that = this;
        let str = that.data.subTitle;
        let firstline;
        let secondline;
        //一行显示14个字，超过一行时
        if (str.length > 14) {
            //第一行截取前14个字符
            firstline = str.substring(0, 14);
            //两行都显示不下
            if (str.length > 28) {
                secondline = str.substr(14, 14) + "...";
            } else {
                //第二行取剩下的
                secondline = str.substr(14, str.length - 14);
            }
        } else {
            //一行就能显示时候
            firstline = str;
        }

        ctx.setFontSize(20);
        ctx.setFillStyle("#666");
        ctx.fillText(firstline, that.data.normalPageX, that.data.subTitlePageY);
        if (secondline) {
            ctx.setFontSize(20);
            ctx.setFillStyle("#666");
            ctx.fillText(
                secondline,
                that.data.normalPageX,
                that.data.subTitlePageY + 30
            );
        }
    },
    //绘制促销信息
    drawMarket: function (ctx, width) {
        let that = this;
        let market = that.data.market;
        let originLeft = width + that.data.normalPageX;
        for (let i = 0; i < market.length; i++) {
            let marketTxt = market[i];
            let adjustWidth = 70 * i;
            ctx.strokeStyle = "#cb4255";
            ctx.strokeRect(originLeft + adjustWidth + 10, that.data.pricePageY - 30, 60, 30);
            ctx.setFontSize(20);
            ctx.setFillStyle("#cb4255");
            ctx.fillText(marketTxt, originLeft + adjustWidth + 20, that.data.pricePageY - 8);
        }
    },
    // 根据文字多少动态计算高度，然后依次画出矩形，文字，横线和小程序码。
    createNewImg: function () {
        let that = this;
        let ctx = wx.createCanvasContext(that.data.canvasId);
        let contentHeight = that.data.boxheight;
        that.drawSquare(ctx, contentHeight);
        that.setData({
            contentHeight: contentHeight
        });
        // let height = 100;
        // for (let item of that.data.thinkList) {
        //   if (item !== "a") {

        //     height += that.data.lineHeight;
        //   }
        // }
        that.drawTitleFont(ctx);
        if (that.data.subTitle && that.data.subTitle.length > 0) {
            that.drawSubTitleFont(ctx);
        }
        //商城logo
        ctx.drawImage(
            that.data.downlogo,
            (that.data.boxWidth - that.data.logoWidth) / 2,
            (that.data.imgPageY - that.data.logoHeight) / 2,
            that.data.logoWidth,
            that.data.logoHeight
        );
        console.log(that.data.logoWidth, that.data.logoHeight, '======高宽');
        if (that.data.goodsInfoImg != "") {
            //商品图片
            ctx.drawImage(
                that.data.goodsInfoImg,
                that.data.normalPageX - 15,
                that.data.imgPageY,
                that.data.imgWidth,
                that.data.imgHeight
            );
        }
        var sharePrice = that.data.shareObj.SharePrice;
        let {
            isLogin,
            NoLoginShowPrice,
            price,
            isDeduction,
            grade,
            productData,
            Currency
        } = that.data
        //判断是否显示分享价格
        if (sharePrice != 0) {
            let priceWidth = 0
            let txt = `` // 价格部分文字内容
            //如果价格为0，积分不为零并且不是抵扣模式下  不显示价格
            if (!(productData.Price == 0 && grade != 0 && !isDeduction)) {
                ctx.setFillStyle("#cb4255");
                ctx.font = "normal normal 30px sans-serif";
                // 填充价格文字
                ctx.font = "normal bold 40px sans-serif";
                let fillPrice = ''
                if (!isLogin && !NoLoginShowPrice) {
                    fillPrice = '请登录后查看价格'
                } else {
                    fillPrice = price
                }
                txt += fillPrice
                ctx.fillText(
                    fillPrice,
                    that.data.normalPageX - 15,
                    that.data.pricePageY
                );
            }
            // 计算价格符号￥ + 价格文字宽度
            // priceWidth = (price == 0|| price == '请登录后查看价格' && grade != 0 && !isDeduction) ? 0 : ctx.measureText(Currency + price).width;
            priceWidth = ctx.measureText(txt)
            //有积分且不是积分抵扣模式下显示
            //积分宽度
            let gradeWidth = 0;
            if (grade != 0 && !isDeduction && price > 0) {
                // 填充积分文字
                ctx.setFillStyle("#cb4255");
                ctx.font = "normal normal 24px sans-serif";
                gradeWidth = ctx.measureText("+" + grade + "积分").width;
                ctx.fillText("+" + grade + "积分", that.data.normalPageX - 2 + priceWidth, that.data.pricePageY)
            }
            //价格区域的总宽度
            let priceTotleWidth = priceWidth + gradeWidth;
            //绘制促销
            that.drawMarket(ctx, priceTotleWidth);
        }
        // 填充小程序码
        ctx.drawImage(
            that.data.qrCode,
            that.data.normalPageX + that.data.windowWidth * 0.43,
            that.data.codePageY,
            that.data.codeWidth,
            that.data.codeHeight
        );
        // 填充长按立即购买文本
        ctx.setFillStyle("#333");
        ctx.font = "normal normal 18px sans-serif";
        ctx.fillText(
            "扫描/长按识别",
            that.data.normalPageX +
            that.data.windowWidth * 0.43 +
            (that.data.codeWidth - 108) / 2,
            that.data.codePageY + that.data.codeWidth + 20
        );
        ctx.draw(false, function () {
            wx.canvasToTempFilePath({
                canvasId: 'canvas',
                success: function (res) {
                    wx.hideLoading();
                    var tempFilePath = res.tempFilePath;
                    that.setData({
                        tempFilePath,
                        saveBtn: true
                    })
                },
                fail: function (err) {
                    console.info(err);
                }
            });
        }); //绘制到canvas
    },

    //下载小程序码
    downloadSkuQrCode: function () {
        let that = this;
        const currentRoute = that.getCurrentPageUrlWithArgs();
        profile.load_wx_qrcode(currentRoute, function (content) {
            if (content != "") {
                var url = "data:image/png;base64," + content;
                that.setData({
                    preQR: url
                })
                util.base64src(url, function (res) {
                    url = res;
                    that.setData({
                        qrCode: url
                    });
                    that.renderCanvas()
                    // that.createNewImg();
                });
            } else {
                that.setData({
                    showPosterShadow: false
                }, function () {
                    util.tips("未能生成小程序码");
                    return;
                })
            }

        });

    },
    renderCanvas() {
        let t = this
        let scale = 2
        getViewListSize(['.center-shadow .cont']).then((res) => {
            let {
                imgDomain,
                logo,
                posterPic,
                productData,
                contentTitle,
                preQR,
                qrCode,
                price,
                isLogin,
                NoLoginShowPrice,
                shareObj
            } = this.data
            let item = {}
            if (res.length > 0) {
                if (res[0].list && res[0].list.length > 0) {
                    item = res[0].list[0][0]
                }
            }
            t.setData({
                boxHeight: item.height * scale,
                boxWidth: item.width * scale
            })
            let showPrice = false
            if (!isLogin && !NoLoginShowPrice && shareObj.SharePrice != 0) {} else if (shareObj.SharePrice != 0) {
                if (price != 0) {
                    showPrice = true
                }
            }
            let data = {
                imgDomain,
                logo,
                posterPic,
                price,
                showPrice,
                contentTitle,
                productData,
                preQR,
                qrCode,
                scale: scale
            }
            let newData = formatCanvasData(data)
            console.log(newData)
            drawCanvas(newData)
            getImgList().then((res) => {
                if (!isEmpty(res)) {
                    t.setData({
                        tempFilePath: res[0].src,
                        saveBtn: true
                    })
                }
            })
        })
    },

    //点击保存到相册
    saveShareImg: function () {
        var that = this;
        wx.showLoading({
            title: '正在保存',
            mask: true,
        })
        wx.previewImage({
            urls: [that.data.tempFilePath],
        });
        wx.saveImageToPhotosAlbum({
            filePath: that.data.tempFilePath,
            success(res) {
                wx.hideLoading();
                // utils.aiCardActionRecord(19);
                wx.showModal({
                    content: '图片已保存到相册，赶紧晒一下吧~',
                    showCancel: false,
                    confirmText: '好的',
                    confirmColor: '#333',
                    success: function (res) {
                        if (res.confirm) {}
                    },
                    fail: function (res) {}
                })
            },
            fail: function (res) {
                wx.hideLoading();
                wx.showToast({
                    title: "保存失败",
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    },
    getCurrentPageUrlWithArgs: function () {
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        const url = currentPage.route;
        const options = currentPage.options;
        let scene = "";
        var storeInfo = authorize.getEntity();
        if (storeInfo) {
            scene = storeInfo.fkFlag + "_" + storeInfo.fkId + "_" + storeInfo.manager.ManagerId;
        }
        let urlWithArgs = options.id ? options.id : 0;
        urlWithArgs += "_" + (options.ptype ? options.ptype : 0);
        urlWithArgs += "_" + (options.productId ? options.productId : 0);
        urlWithArgs += "_" + (options.discountid ? options.discountid : 0);
        urlWithArgs += "_" + (options.discounttype ? options.discounttype : 0);
        // urlWithArgs += "_" + scene;
        // console.log(urlWithArgs,'========urlWithArgs',scene);
        return {
            url,
            urlWithArgs
        }
    },
    /**显示多规则 */
    onShowGoodsModal(e) {
        var that = this;
        e = e.detail;
        let {
            addr,
            priceDigits,
            decimalDigits,
            quantityDigits,
            isScanty,
            hasMaket
        } = this.data;
        that.fasterComponent.setData({
            item: e.product,
            isScanty: isScanty,
            quantityDigits: quantityDigits,
            priceDigits: priceDigits,
            decimalDigits: decimalDigits,
            areaCode: addr.code,
            hasMaket: hasMaket,
            addCompleted: function (goods) {
                that.onAddCartCompleted({
                    detail: {
                        product: goods,
                        idx: e.idx
                    }
                });
            }
        });
        that.fasterComponent.onShowGoodsModal(e);
    },
    /**
     * 加入完成后调用，更新界面显示数量
     */
    onAddCartCompleted(e) {
        e = e.detail;
        let key = "guessList[" + e.idx + "]";
        this.setData({
            [key]: e.product
        });
    },
    lookImg: function (e) {
        var list = e.detail.imgsList;
        var index = e.detail.index;
        this.setData({
            showModalImg: true,
            imgsList: list,
            idx: index
        })
        // console.log(e);
    },
    closeImg() {
        this.setData({
            showModalImg: false
        })
    },
    bindLabel(e) {
        var id = e.currentTarget.dataset.id;
        router.navigate({
            path: "promotionDetail",
            params: {
                id: id
            }
        })
    },
    wxParseTagATap(e) {
        let event = e.detail.event || {
            currentTarget: {
                dataset: {
                    src: ''
                }
            }
        }
        var url = event.currentTarget.dataset.src;
        theme.linkTo(url);
    },
    /**
     * 更多系列，点击后刷新商品信息
     */
    changeProductByGroup(e) {
        let id = e.detail.id
        router.redirect({
            path: "productDetail",
            params: {
                id
            }
        })
    },
    /**
     * 跳转登录页面
     */
    toLogin() {
        let pathUrl = this.data.pathUrl
        util.setBeforeLoginData()
        router.redirect({
            path: "login",
            params: {
                role: "store",
                type: pathUrl
            }
        })
    },
    //获取优惠券组件传过来的值
    handleGetPopData(e){
        this.setData({
            describes:JSON.parse(e.detail),
            showExplainPop:true
        })
    },
    //关闭弹框
    handleColsePop(){
        this.setData({
            showExplainPop:false
        })
    }

})